package com.hwxm.ltim.controller;

import com.hwxm.ltim.common.Result;
import com.hwxm.ltim.entity.ChatMessage;
import com.hwxm.ltim.service.ChatMessageService;
import com.hwxm.ltim.util.ChannelManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Autowired
    private ChatMessageService chatMessageService;

    /**
     * 获取聊天历史记录
     */
    @GetMapping("/history")
    public Result<List<ChatMessage>> getChatHistory(
            @RequestParam Long userId1,
            @RequestParam Long userId2,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        try {
            List<ChatMessage> messages = chatMessageService.getChatHistory(userId1, userId2, pageNum, pageSize);
            return Result.success(messages);
        } catch (Exception e) {
            log.error("获取聊天历史失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取在线用户数
     */
    @GetMapping("/online-count")
    public Result<Map<String, Integer>> getOnlineCount() {
        try {
            int count = ChannelManager.getOnlineCount();
            Map<String, Integer> data = new HashMap<>();
            data.put("count", count);
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取在线用户数失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查用户是否在线
     */
    @GetMapping("/online/{userId}")
    public Result<Map<String, Boolean>> checkOnline(@PathVariable Long userId) {
        try {
            boolean online = ChannelManager.isOnline(userId);
            Map<String, Boolean> data = new HashMap<>();
            data.put("online", online);
            return Result.success(data);
        } catch (Exception e) {
            log.error("检查在线状态失败", e);
            return Result.error(e.getMessage());
        }
    }
}

